// components/index-goods-item/index.js
let cart_js = require("../../utils/cart.js");

// 首页单行商品
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    item: {
      type: Object,
      value: null,
    },
    selectedCartInfo: {
      type: Object,
      value: null
    }
  },

  observers: {
    'item': function (item) {
      this.initData(item);
    },
    selectedCartInfo(info) {
      //获取该商品在购物车中的数量
      this.getGoodsCountInCart();
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    promotionPrice: '', //促销价格，活动商品或者没有活动商品的现价
    price: '', //原价或者或者划线价
    savePrice: 0, //省多少钱
    number: -1, //该商品在购物车中的数量
    skuIdList: [],
    discount: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //初始化数据
    initData: function (item) {
      let tmpPromotionPrice = '';
      let tmpPrice = '';
      let tmpSavePrice = 0;
      let tmpDiscount = 0;

      if (item.type == 0) {
        //只有原价
        tmpPromotionPrice = item.minPrice;
        tmpPrice = item.minCrossedPrice;

      } else {
        //促销或者团购的话有原价和促销价
        tmpPromotionPrice = item.minPromotionPrice;
        tmpPrice = item.minPrice;
      }

      //无营销活动划线价 - 售价
      //有营销活动划线价 - 售价
      tmpSavePrice = (parseFloat(item.minCrossedPrice) - parseFloat(tmpPromotionPrice)).toFixed(2);

      //无营销活动 售价/划线价
      //有营销活动 活动价 / 划线价
      if (item.minCrossedPrice != 0) {
        tmpDiscount = ((parseFloat(tmpPromotionPrice) / parseFloat(item.minCrossedPrice)) * 10).toFixed(1);
      }

      console.log(this.data.item)
      console.log(tmpSavePrice)
      console.log(tmpDiscount)

      this.setData({
        promotionPrice: tmpPromotionPrice,
        price: tmpPrice,
        discount: tmpDiscount,
        savePrice: tmpSavePrice
      });
    },
    // 获取该商品在购物车中的数量
    getGoodsCountInCart() {
      //获取该商品在购物车中的数量
      if (this.data.selectedCartInfo.count == 0) {
        this.setData({
          number: -1
        })
        return;
      };
      //求两个集合的交集
      let tmpNumber = 0;
      let tmpSkuList = [];
      for (let i = 0; i < this.data.item.skuList.length; i++) {
        let skuId = this.data.item.skuList[i].id;
        for (let j = 0; j < this.data.selectedCartInfo.skuList.length; j++) {
          if (this.data.selectedCartInfo.skuList[j].skuId == skuId) {
            tmpNumber += this.data.selectedCartInfo.skuList[j].num;
            let arr = new Array(this.data.selectedCartInfo.skuList[j].num).fill(skuId)
            tmpSkuList.push(...arr);
          }
        }
      }
      if (tmpNumber > 0) {
        this.setData({
          number: tmpNumber,
          skuIdList: tmpSkuList
        })
      }
    },
    onAdd: function () {
      this.triggerEvent('add', null, {});
    },
    onNumber() {

    },
    onMinus: function () {
      this.triggerEvent('minus', {
        num: this.data.number,
        skuId: this.data.skuIdList[0]
      }, null);
    },
  }
})